<template>
  <div>
    <s-header :name="'在线聊天'"></s-header>
    <nav-bar></nav-bar>
    <div class="chatArea">
      <div v-for="(item,index) in chatList" :key="index">
        <div style="display:flex;justify-content: left;margin:10px" v-if="item.fromId=== userId">
          <div>
            <img src="../assets/img/default_icon.png" class="avatarImg">
          </div>
          <div style="margin-left: 10px">
            <div style="text-align: left" class="chatName">
              {{ userName }}
            </div>
            <div class="chatMessage chatContent">
              {{item.sendContent}}
            </div>
          </div>
        </div>
        <div style="display: flex;justify-content: right;margin:10px" v-else>
          <div>
            <img v-if="item.fromUserName==='kf01'" src="../assets/img/kefu.svg" class="avatarImg">
            <img v-else src="../assets/img/avatar.jpeg" class="avatarImg">
          </div>
          <div style="margin-left: 10px">
            <div style="text-align: left" class="chatName">
              {{ item.fromUserName }}
            </div>
            <div class="chatMessage chatContent" v-html="item.sendContent" style="background-color: lightseagreen">
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="chatBottom">
      <div style="text-align: right">
        <van-button type="info" @click="transfer" style="margin: 5px" native-type="submit" icon="manager-o">转人工
        </van-button>
        <van-button type="primary" @click="sendMessage" style="margin: 5px" native-type="submit">发送消息</van-button>
      </div>
      <van-field
        v-model="messageInput"
        rows="3"
        autosize
        type="textarea"
        maxlength="100"
        placeholder="请输入消息"
        show-word-limit
      />
    </div>
  </div>
</template>
<script lang="js">

import navBar from "@/components/NavBar.vue";
import sHeader from "@/components/SimpleHeader.vue";
import {getUserInfo} from '@/service/user'
import {getAskMessage} from '@/service/chat'
import {Toast} from "vant";

export default {
  name: 'Chat',
  components: {sHeader, navBar},
  data() {
    return {
      userName:"",
      userId:null,
      baseUrl: "ws://192.168.31.186:9096/websocket/chat/",
      chatList: [],
      chatForm: {
        id: null,
        fromId: null,
        toId: null,
        fromUserName: "",
        toUserName: "",
        sendContent: "",
        sendTime: null
      },
      messageInput: "",
      ws: null,
      isTalkToRobot: true,
      robotReplyMessage: "抱歉,您的问题暂时无法回复,请点击【转人工】按钮进行转接"
    }
  },
  methods: {
    transfer() {
      this.initWebSocket();
    },
    sendMessage() {
      const message = this.messageInput.trim().toString();
      if (message.length === 0) {
        Toast("请输入内容后发送消息");
        return;
      }
      this.chatForm.sendContent = this.messageInput.trim().toString();
      this.chatForm.sendTime = this.parseTime(new Date());
      let sendMessage;
      if (this.ws) {
        this.chatForm.toUserName = "kf01";
        sendMessage = JSON.parse(JSON.stringify(this.chatForm));
        this.ws.send(JSON.stringify(sendMessage));
      } else {
        this.chatForm.toUserName = "机器人";
        sendMessage = JSON.parse(JSON.stringify(this.chatForm));
        getAskMessage(this.chatForm).then(res => {
          this.chatList.push(res.data);
        })
        this.sendMessageAuto = sendMessage.sendContent;
      }
      this.chatList.push(sendMessage);
      this.messageInput = "";
    },

    async initWebSocket() {
      Toast.loading({
        message: "正在为您转接,请稍等.......",
        forbidClick: true,
      });
      this.ws = new WebSocket(`${this.baseUrl}${this.userId}`)
      this.ws.onopen = this.webSocketOpen
      this.ws.onmessage = this.webSocketMessage
      this.ws.onclose = this.webSocketClose
    },
    webSocketOpen() {
      Toast("上线")
      if (this.sendMessageAuto != null) {
        const chatForm = {
          id: null,
          fromId: this.userId,
          toId: "1",
          fromUserName: this.userName,
          toUserName: "kf01",
          sendContent: this.sendMessageAuto.trim().toString(),
          sendTime: this.parseTime(new Date())
        }
        this.ws.send(JSON.stringify(chatForm));
      }
    },
    webSocketMessage(message) {
      const parseMessage = JSON.parse(message.data);

      this.chatList.push(parseMessage);
    },
    webSocketClose() {
      Toast("下线")
    },
    initTalk() {
      getAskMessage({}).then(res => {
        this.chatList.push(res.data);
      })
    }
  },
  async mounted() {
    const res = (await getUserInfo()).data;
    this.userId = res.userId;
    this.userName = res.nickName;
    this.chatForm.fromId = res.userId;
    this.chatForm.fromUserName = res.nickName;
    this.chatForm.toId = 1;
    this.initTalk();
  }

}
</script>

<style>
.avatarImg {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.chatArea {
  height: calc(100% - 300px);
  margin-top: 44px;
  background-color: lightgray;
  scroll-behavior: auto;
  overflow: auto;
}

.chatMessage {
  border-radius: 10px;
  background-color: white;
  margin: 6px;
  padding: 6px;
}

.chatName {
  font-size: .4rem;
  font-weight: bold;
  color: gray;
}

.chatContent {
  font-size: .4rem;
  color: black;
}
</style>
